package com.mango.Service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.mango.Service.SendSmsService;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/8/9 22:12
 */
@Service
public class SendSmsImpl implements SendSmsService {

    /**
     * @param phoneNum     发送的手机号
     * @param TemplateCode 短信模板的code
     * @param code         验证码
     * @return
     * accessKeyId 你自己的 accessKeyId      相当于账号
	 * accessSecret  在创建用户时的 accessSecret 相当于密码
     */
    @Override
    public boolean sendSms(String phoneNum, String TemplateCode, Map<String, Object> code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
        IAcsClient client = new DefaultAcsClient(profile);
        //构建请求
        CommonRequest request = new CommonRequest();
        //不要改
        request.setSysMethod(MethodType.POST);
        //不能改 改了就会报错
        request.setSysDomain("dysmsapi.aliyuncs.com");
        //不能改  改了就会报错
        request.setSysVersion("2017-05-25");
        //一般也不会该改
        request.setSysAction("SendSms");
        //自定义的参数(手机号，验证码，模板，签名)
        //参数名称不要乱写
        //手机号
        request.putQueryParameter("PhoneNumbers", phoneNum);
        //签名名称
        request.putQueryParameter("SignName", "签名名称");
        //模板code
        request.putQueryParameter("TemplateCode", TemplateCode);
        //短信验证码
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            //这个是他自带的判断他发送的是否成功，成功就直接返回
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
